<template>
    <view class="container">
        <!-- 搜索栏 -->
        <view class="search-bar">
            <view class="search-input">
                <image src="/static/images/admin/search.png"></image>
                <input 
                    type="text"
                    v-model="searchKey"
                    placeholder="搜索设备编号/位置"
                    @confirm="handleSearch"
                />
            </view>
            <view class="filter-btn" @tap="showFilter">
                <image src="/static/images/admin/filter.png"></image>
            </view>
        </view>

        <!-- 状态标签 -->
        <scroll-view class="status-tags" scroll-x>
            <view 
                class="tag"
                :class="{ active: currentStatus === status.value }"
                v-for="status in statusOptions"
                :key="status.value"
                @tap="filterByStatus(status.value)"
            >
                {{ status.label }}
            </view>
        </scroll-view>

        <!-- 设备列表 -->
        <scroll-view 
            class="device-list"
            scroll-y
            @scrolltolower="loadMore"
            :refresher-enabled="true"
            :refresher-triggered="refreshing"
            @refresherrefresh="refresh"
        >
            <view 
                class="device-item"
                v-for="item in deviceList"
                :key="item.id"
                @tap="goToDetail(item)"
            >
                <view class="device-info">
                    <view class="device-no">{{ item.deviceNo }}</view>
                    <view class="device-status" :class="item.status">
                        {{ getStatusText(item.status) }}
                    </view>
                </view>
                <view class="location">
                    <image src="/static/images/admin/location.png"></image>
                    <text>{{ item.hospitalName }} {{ item.departmentName }}</text>
                </view>
                <view class="device-data">
                    <view class="data-item">
                        <text class="label">今日收入</text>
                        <text class="value">¥{{ item.todayIncome || '0.00' }}</text>
                    </view>
                    <view class="data-item">
                        <text class="label">使用次数</text>
                        <text class="value">{{ item.useCount || 0 }}</text>
                    </view>
                    <view class="data-item">
                        <text class="label">故障次数</text>
                        <text class="value">{{ item.faultCount || 0 }}</text>
                    </view>
                </view>
                <view class="actions">
                    <button 
                        class="action-btn"
                        :class="{ disabled: !item.canLock }"
                        @tap.stop="handleLock(item)"
                    >
                        {{ item.status === 'locked' ? '解锁' : '锁定' }}
                    </button>
                    <button 
                        class="action-btn"
                        @tap.stop="handleMaintain(item)"
                    >
                        {{ item.status === 'maintaining' ? '完成维护' : '维护' }}
                    </button>
                </view>
            </view>

            <!-- 加载更多 -->
            <view class="loading" v-if="loading">加载中...</view>
            <view class="no-more" v-if="noMore">没有更多了</view>
        </scroll-view>

        <!-- 筛选弹窗 -->
        <uni-popup ref="filterPopup" type="right">
            <view class="filter-popup">
                <view class="popup-header">
                    <text>筛选条件</text>
                    <view class="close-btn" @tap="hideFilter">×</view>
                </view>
                <view class="filter-content">
                    <view class="filter-section">
                        <view class="section-title">医院</view>
                        <view class="hospital-list">
                            <view 
                                class="hospital-item"
                                :class="{ active: selectedHospital === hospital.id }"
                                v-for="hospital in hospitalList"
                                :key="hospital.id"
                                @tap="selectHospital(hospital.id)"
                            >
                                {{ hospital.name }}
                            </view>
                        </view>
                    </view>
                    <view class="filter-section">
                        <view class="section-title">时间范围</view>
                        <picker 
                            mode="date" 
                            :value="dateRange.start"
                            @change="handleStartDateChange"
                        >
                            <view class="date-picker">
                                <text>开始日期</text>
                                <text>{{ dateRange.start || '请选择' }}</text>
                            </view>
                        </picker>
                        <picker 
                            mode="date" 
                            :value="dateRange.end"
                            @change="handleEndDateChange"
                        >
                            <view class="date-picker">
                                <text>结束日期</text>
                                <text>{{ dateRange.end || '请选择' }}</text>
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="popup-footer">
                    <button class="reset-btn" @tap="resetFilter">重置</button>
                    <button class="confirm-btn" @tap="confirmFilter">确定</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { getDeviceList, lockDevice, unlockDevice, setMaintainStatus } from '@/api/device'
import store from '@/utils/store'

export default {
    data() {
        return {
            searchKey: '',
            currentStatus: 'all',
            statusOptions: [
                { label: '全部', value: 'all' },
                { label: '空闲', value: 'idle' },
                { label: '使用中', value: 'using' },
                { label: '已锁定', value: 'locked' },
                { label: '维护中', value: 'maintaining' },
                { label: '故障', value: 'fault' }
            ],
            deviceList: [],
            page: 1,
            pageSize: 10,
            loading: false,
            refreshing: false,
            noMore: false,
            selectedHospital: '',
            hospitalList: [],
            dateRange: {
                start: '',
                end: ''
            }
        }
    },
    onLoad() {
        // 检查权限
        if (!store.isAdmin()) {
            uni.showToast({
                title: '无权限访问',
                icon: 'none'
            })
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/index/index'
                })
            }, 1500)
            return
        }
        
        this.loadDeviceList()
        this.loadHospitalList()
    },
    methods: {
        // 加载设备列表
        async loadDeviceList(reset = false) {
            if (this.loading) return
            
            try {
                this.loading = true
                if (reset) {
                    this.page = 1
                    this.deviceList = []
                    this.noMore = false
                }
                
                const params = {
                    page: this.page,
                    pageSize: this.pageSize,
                    keyword: this.searchKey,
                    status: this.currentStatus === 'all' ? '' : this.currentStatus,
                    hospitalId: this.selectedHospital,
                    startDate: this.dateRange.start,
                    endDate: this.dateRange.end
                }
                
                const res = await getDeviceList(params)
                this.deviceList = [...this.deviceList, ...res.list]
                this.noMore = res.list.length < this.pageSize
                
                if (reset && res.list.length === 0) {
                    uni.showToast({
                        title: '暂无数据',
                        icon: 'none'
                    })
                }
            } catch (error) {
                uni.showToast({
                    title: error.message || '加载失败',
                    icon: 'none'
                })
            } finally {
                this.loading = false
                this.refreshing = false
            }
        },
        
        // 处理搜索
        handleSearch() {
            this.loadDeviceList(true)
        },
        
        // 状态筛选
        filterByStatus(status) {
            this.currentStatus = status
            this.loadDeviceList(true)
        },
        
        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                idle: '空闲',
                using: '使用中',
                locked: '已锁定',
                maintaining: '维护中',
                fault: '故障'
            }
            return statusMap[status] || status
        },
        
        // 跳转详情
        goToDetail(device) {
            uni.navigateTo({
                url: `/pages/admin/device/detail?id=${device.id}`
            })
        },
        
        // 处理锁定/解锁
        async handleLock(device) {
            if (!device.canLock) return
            
            try {
                const action = device.status === 'locked' ? '解锁' : '锁定'
                await uni.showModal({
                    title: '提示',
                    content: `确定要${action}该设备吗？`
                })
                
                const api = device.status === 'locked' ? unlockDevice : lockDevice
                await api(device.id)
                
                // 更新设备状态
                const index = this.deviceList.findIndex(item => item.id === device.id)
                if (index !== -1) {
                    this.deviceList[index].status = device.status === 'locked' ? 'idle' : 'locked'
                }
                
                uni.showToast({
                    title: `${action}成功`,
                    icon: 'success'
                })
            } catch (error) {
                uni.showToast({
                    title: error.message || `${action}失败`,
                    icon: 'none'
                })
            }
        },
        
        // 处理维护状态
        async handleMaintain(device) {
            try {
                const action = device.status === 'maintaining' ? '完成维护' : '开始维护'
                await uni.showModal({
                    title: '提示',
                    content: `确定要${action}吗？`
                })
                
                await setMaintainStatus(device.id, device.status !== 'maintaining')
                
                // 更新设备状态
                const index = this.deviceList.findIndex(item => item.id === device.id)
                if (index !== -1) {
                    this.deviceList[index].status = device.status === 'maintaining' ? 'idle' : 'maintaining'
                }
                
                uni.showToast({
                    title: `${action}成功`,
                    icon: 'success'
                })
            } catch (error) {
                uni.showToast({
                    title: error.message || '操作失败',
                    icon: 'none'
                })
            }
        },
        
        // 加载更多
        loadMore() {
            if (this.noMore || this.loading) return
            this.page++
            this.loadDeviceList()
        },
        
        // 刷新
        refresh() {
            this.refreshing = true
            this.loadDeviceList(true)
        },
        
        // 显示筛选弹窗
        showFilter() {
            this.$refs.filterPopup.open()
        },
        
        // 隐藏筛选弹窗
        hideFilter() {
            this.$refs.filterPopup.close()
        },
        
        // 加载医院列表
        async loadHospitalList() {
            try {
                const res = await getHospitalList()
                this.hospitalList = res
            } catch (error) {
                console.error('加载医院列表失败', error)
            }
        },
        
        // 选择医院
        selectHospital(id) {
            this.selectedHospital = id
        },
        
        // 处理开始日期变化
        handleStartDateChange(e) {
            this.dateRange.start = e.detail.value
        },
        
        // 处理结束日期变化
        handleEndDateChange(e) {
            this.dateRange.end = e.detail.value
        },
        
        // 重置筛选条件
        resetFilter() {
            this.selectedHospital = ''
            this.dateRange = {
                start: '',
                end: ''
            }
        },
        
        // 确认筛选
        confirmFilter() {
            this.hideFilter()
            this.loadDeviceList(true)
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: env(safe-area-inset-bottom);
    
    .search-bar {
        padding: 20rpx;
        background-color: #fff;
        display: flex;
        align-items: center;
        position: sticky;
        top: 0;
        z-index: 100;
        
        .search-input {
            flex: 1;
            height: 72rpx;
            background: #f5f5f5;
            border-radius: 36rpx;
            display: flex;
            align-items: center;
            padding: 0 30rpx;
            margin-right: 20rpx;
            
            image {
                width: 32rpx;
                height: 32rpx;
                margin-right: 10rpx;
            }
            
            input {
                flex: 1;
                font-size: 28rpx;
            }
        }
        
        .filter-btn {
            width: 72rpx;
            height: 72rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            
            image {
                width: 40rpx;
                height: 40rpx;
            }
        }
    }
    
    .status-tags {
        white-space: nowrap;
        padding: 20rpx;
        background: #fff;
        border-bottom: 1rpx solid #eee;
        
        .tag {
            display: inline-block;
            padding: 10rpx 30rpx;
            margin-right: 20rpx;
            font-size: 28rpx;
            color: #666;
            background: #f5f5f5;
            border-radius: 28rpx;
            
            &.active {
                background: #07c160;
                color: #fff;
            }
            
            &:last-child {
                margin-right: 0;
            }
        }
    }
    
    .device-list {
        height: calc(100vh - 220rpx);
        
        .device-item {
            margin: 20rpx;
            padding: 30rpx;
            background: #fff;
            border-radius: 12rpx;
            
            .device-info {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20rpx;
                
                .device-no {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                }
                
                .device-status {
                    padding: 6rpx 20rpx;
                    border-radius: 20rpx;
                    font-size: 24rpx;
                    
                    &.idle {
                        background: #e8f5e9;
                        color: #4caf50;
                    }
                    
                    &.using {
                        background: #e3f2fd;
                        color: #2196f3;
                    }
                    
                    &.locked {
                        background: #fff3e0;
                        color: #ff9800;
                    }
                    
                    &.maintaining {
                        background: #f3e5f5;
                        color: #9c27b0;
                    }
                    
                    &.fault {
                        background: #ffebee;
                        color: #f44336;
                    }
                }
            }
            
            .location {
                display: flex;
                align-items: center;
                margin-bottom: 20rpx;
                
                image {
                    width: 32rpx;
                    height: 32rpx;
                    margin-right: 10rpx;
                }
                
                text {
                    font-size: 28rpx;
                    color: #666;
                }
            }
            
            .device-data {
                display: flex;
                margin-bottom: 30rpx;
                
                .data-item {
                    flex: 1;
                    text-align: center;
                    
                    .label {
                        font-size: 24rpx;
                        color: #999;
                        margin-bottom: 10rpx;
                        display: block;
                    }
                    
                    .value {
                        font-size: 32rpx;
                        color: #333;
                        font-weight: bold;
                    }
                }
            }
            
            .actions {
                display: flex;
                gap: 20rpx;
                
                .action-btn {
                    flex: 1;
                    height: 80rpx;
                    line-height: 80rpx;
                    text-align: center;
                    background: #f5f5f5;
                    border-radius: 40rpx;
                    font-size: 28rpx;
                    color: #333;
                    
                    &.disabled {
                        opacity: 0.5;
                    }
                }
            }
        }
        
        .loading, .no-more {
            text-align: center;
            padding: 30rpx;
            font-size: 28rpx;
            color: #999;
        }
    }
    
    .filter-popup {
        width: 600rpx;
        height: 100vh;
        background: #fff;
        
        .popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 30rpx;
            border-bottom: 1rpx solid #eee;
            
            text {
                font-size: 32rpx;
                font-weight: bold;
            }
            
            .close-btn {
                font-size: 40rpx;
                color: #999;
                padding: 10rpx;
            }
        }
        
        .filter-content {
            padding: 30rpx;
            
            .filter-section {
                margin-bottom: 40rpx;
                
                .section-title {
                    font-size: 28rpx;
                    color: #333;
                    margin-bottom: 20rpx;
                }
                
                .hospital-list {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 20rpx;
                    
                    .hospital-item {
                        padding: 10rpx 30rpx;
                        background: #f5f5f5;
                        border-radius: 28rpx;
                        font-size: 28rpx;
                        color: #666;
                        
                        &.active {
                            background: #07c160;
                            color: #fff;
                        }
                    }
                }
                
                .date-picker {
                    height: 88rpx;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 0 30rpx;
                    background: #f5f5f5;
                    border-radius: 12rpx;
                    margin-bottom: 20rpx;
                    
                    text {
                        font-size: 28rpx;
                        color: #333;
                        
                        &:last-child {
                            color: #666;
                        }
                    }
                }
            }
        }
        
        .popup-footer {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 30rpx;
            display: flex;
            gap: 20rpx;
            background: #fff;
            border-top: 1rpx solid #eee;
            
            button {
                flex: 1;
                height: 88rpx;
                line-height: 88rpx;
                border-radius: 44rpx;
                font-size: 32rpx;
                
                &.reset-btn {
                    background: #f5f5f5;
                    color: #333;
                }
                
                &.confirm-btn {
                    background: #07c160;
                    color: #fff;
                }
            }
        }
    }
}
</style> 